package com.haiqiu.file.ftp.config;

import com.haiqiu.file.oss.config.OssConfig;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author HaiQiu
 * @since 2022/11/29
 * ftp工厂连接池
 */
@Component
public class FtpClientFactory implements PooledObjectFactory<FTPClient> {

    private final Logger log = LoggerFactory.getLogger(OssConfig.class);
    @Autowired
    private FtpConfig ftpConfig;

    @Override
    public PooledObject<FTPClient> makeObject() throws Exception {
        if (!ftpConfig.getEnable()){
            throw new RuntimeException("FTP服务未启用");
        }
        FTPClient ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(1000 * 10);
        try {
            ftpClient.connect(ftpConfig.getHost(), ftpConfig.getPort());
            ftpClient.login(ftpConfig.getUsername(), ftpConfig.getPassword());
            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                log.warn("未连接到FTP，用户名或密码错误，username:{},password:{}",ftpConfig.getUsername(),ftpConfig.getPassword());
                ftpClient.disconnect();
                throw new RuntimeException("未连接到FTP，用户名或密码错误。");
            }
            ftpClient.setControlEncoding(ftpConfig.getEncoded()); // 中文转码
            //是否设置被动模式
            if (ftpConfig.isPassiveMode()) {
                ftpClient.enterLocalPassiveMode();
            }
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);//设置传输方式为流方式
            ftpClient.changeWorkingDirectory(ftpConfig.getCurrentPath()); // 设置文件操作目录
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);// 设置文件类型，二进制
            ftpClient.setBufferSize(3072); // 设置缓冲区大小
            log.info("FTP初始化连接成功：{}，username:{}", ftpConfig.getHost(), ftpConfig.getUsername());
        } catch (Exception e) {
            log.error("makeClient exception", e);
        }
        return new DefaultPooledObject<>(ftpClient);
    }

    @Override
    public void destroyObject(PooledObject<FTPClient> pooledObject) throws Exception {
        FTPClient ftpClient = pooledObject.getObject();
        try {
            if (ftpClient != null && ftpClient.isConnected()) {
                ftpClient.disconnect();
                log.info("销毁ftp连接");
            }
        } catch (Exception e) {
            log.error("ftpClient logout exception", e);
        } finally {
            try {
                if (ftpClient != null) {
                    ftpClient.disconnect();
                    log.info("销毁ftp连接");
                }
            } catch (Exception e2) {
                log.error("ftpClient disconnect exception", e2);
            }
        }
    }

    @Override
    public boolean validateObject(PooledObject<FTPClient> pooledObject) {
        try {
            return pooledObject.getObject().sendNoOp();
        } catch (Exception e) {
            log.error("ftpClient validate exception", e);
        }
        return false;
    }

    @Override
    public void activateObject(PooledObject<FTPClient> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<FTPClient> pooledObject) throws Exception {

    }
}
